(function ($) {
  $.ajaxSetup({
    cache: false, //关闭AJAX相应的缓存
  });
  var alertTimer = null;

  $.extend({
    myAlert: function (options) {
      if (!options) options = {};
      layui.use('layer', function () {
        var layer = layui.layer;
        var icon = 0;
        if (options.layerType == 'tip') {
          var layerTip = layer.tips(options.msg, options.dom, {
            tips: [options.direction || 1, options.color || '#409efe']
          })
          return layerTip;
        }
        switch (options.type) {
          case "danger":
            icon = 2
            break;
          case "warning":
            icon = 0
            break;
          case "info":
            icon = 6;
            break;
          case "success":
            icon = 1
            break;
          default:
            break;
        }
        layer.msg(options.message || "", {
          icon: icon,
          time: options.duration || 3000 //3秒关闭（如果不配置，默认是3秒）
        }, function () {
          if (options.callback) {
            options.callback();
          }
        });

      });
    },
    myConfirm: function (options) {
      if (!options) options = {};

      layui.use('layer', function () {
        layer.open({
          type: 1,
          title: options.title || '提示',
          content: options.message,
          area: [options.width || '500px', options.height || 'auto'],
          btn: options.btn || ['确认', '取消'],
          success: function (layero, index) {

            if (options.showCallback) {
              options.showCallback();
            }
          },
          yes: function (layero, index) {
            layer.close(layero);
            if (options.confirmCallback) {
              options.confirmCallback();
            }
          },
          btn2: function (layero, index) {
            if (options.cancelCallback) {
              options.cancelCallback();
            }
          },
          cancel: function (layero, index) {//右上角关闭回调
            //点击取消回调
            if (options.cancelCallback) {
              options.cancelCallback();
            }
            //叉叉回调
            if (options.closeCallback) {
              options.closeCallback();
            }
          }
          //这里content是一个普通的String
        });
      });
    },
    initTable: function (options) {
      var settings = {
        striped: true, //隔行高亮
        search: options.search || false,
        showRefresh: options.showRefresh || false,
        queryParams:
          options.params ||
          function (params) {
            return params;
          },
        cache: options.cache || false,
        ajaxOptions: options.ajaxOptions || {},
        dataType: options.dataType || "json",
        contentType: options.contentType || "application/json",
        url: options.url || "",
        method: options.method || "get",
        pagination: options.pagination || false,
        onlyInfoPagination: false, //只显示明细不显示右侧分页
        sortOrder: false,
        sidePagination: options.sidePagination || "client", //server
        pageNumber: options.pageNumber || 1,
        pageSize: options.pageSize || 10,
        pageList: options.pageList || [10, 20, 50, 100],
        search: false,
        // detailView: true,
        paginationPreText: options.paginationPreText || "下一页",
        paginationNextText: options.paginationNextText || "上一页",
        columns: options.columns,
        data: options.data || [],
        // fixedColumns: {
        //   leftColumns: 1, //固定列
        //   rightColumns: 1, //固定列
        // },
        onAll: function (data) {
          if (options.pagination) {
            $(".fixed-table-pagination > .pagination").show();
          }
          if (options.callback) {
            options.callback(data);
          }
        },
        onLoadSuccess: function () { },
        onLoadError: function () { },
      };
      $("#" + options.tableId).bootstrapTable(settings);
    },
    layuiTable: function (options) {
      var pro = $.Deferred();
      layui.use(function () {
        //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
        //得到各种内置组件
        var table = layui.table,
          layer = layui.layer,
          dropdown = layui.dropdown; //表格
        pro.resolve(table)
        //执行一个 table 实例
        table.render({
          elem: "#" + options.id,
          // height: "auto",
          limit: 10,
          limits: [10, 20, 50, 100],
          // url: "/static/demo/table/user/index.html", //数据接口
          // method: "get",
          // where: {},
          // title: "用户表",
          text: "暂无数据",
          loading: false,
          page: true, //开启分页
          toolbar: false, //'default' //开启工具栏
          totalRow: false, //开启合计行
          // skin: "row", //行边框风格 row,line,nob
          even: false, //开启隔行背景
          size: "lg", //小尺寸的表格 sm
          cols: options.cols ? [options.cols] : [[]],
          data: options.data || [],
          done: function (res, curr, count) {
            if (options.done) {
              options.done(res, table);
            }
          },
          error: function () { },
        });
        //监听行工具事件
        table.on("tool(bootstrapTable)", function (obj) {
          //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
          var data = obj.data, //获得当前行数据
            layEvent = obj.event; //获得 lay-event 对应的值
          if (layEvent === "detail") {
            layer.msg("查看操作");
          }
        });
      });
    },
    /**附件上传 */
    initUploader(options) {
      var size = 5;
      var settings = {
        dnd: options.dnd || undefined,//拖拽的容器
        disableGlobalDnd: options.dnd ? true : false,//是否禁掉整个页面的拖拽功能，如果不禁用，图片拖进来的时候会默认被浏览器打开
        swf: 'static/plugin/webuploader/Uploader.swf',
        chunked: false,//分片
        chunkSize: 5242880,//分片大小
        chunkRetry: 2,//断开链接后，允许自动上传的次数
        auto: options.auto || false,//自动上传
        threads: 3,//上传并发数
        formData: {},//文件上传请求的参数表
        method: 'POST',
        sendAsBinary: false,//是否已二进制的流的方式发送文件
        fileNumLimit: options.fileNums || undefined,//验证文件总数量, 超出则不允许加入队列
        fileSizeLimit: undefined,//验证总文件大小
        fileSingleSizeLimit: undefined,//单个文件大小验证 2 * 1024 * 1024
        duplicate: options.duplicate || false,//去重， 根据文件名字、文件大小和最后修改时间来生成hash Key
        pick: {
          id: options.picker || undefined,
          innerHTML: options.btnText || '',
          multiple: options.multiple || false,//多文件选择
        },
        accept: {
          title: '',//文件类型描述描述
          extensions: 'gif,jpg,jpeg,bmp,png,zip,rar,docx,doc,xls,xlsx,pdf',//允许的文件后缀，不带点，多个用逗号分割
          mimeTypes: options.mimeTypes || '*',//'image/*,application/*',//多个用逗号分割
        }
      }
      var uploaderFiles = [];
      //文件大小
      if (options.fileSize) {
        size = options.fileSize;
      }

      //上传组件
      if (!options.viewType) {
        options.viewType = 'list'
      } else {
        settings.fileNumLimit = 1
      }
      //文件类型
      if (options.fileTypes) {
        if (typeof (options.fileTypes) == 'string') {
          settings.accept.extensions = options.fileTypes
        } else if (typeof (options.fileTypes) == 'object') {
          settings.accept.extensions = options.fileTypes.join(',')
        }
      }
      //文件大小 默认限制5M
      settings.fileSingleSizeLimit = size * 1024 * 1024;
      var uploader = new WebUploader.Uploader(settings);
      var filePicker = $(options.picker).parent('.fileItem');
      function initHtml(fileObj) {
        var html = '';
        if (!fileObj.type) {
          return html;
        }
        fileObj.type = fileObj.type.toLowerCase();
        if (fileObj.id) {
          html += '<div class="item" data-id="' + fileObj.id + '" title="' + fileObj.name + '">'
        } else {
          html += '<div class="item" data-id="' + fileObj.fileId + '" data-file="' + fileObj.base64 + '" title="' + fileObj.name + '">'
        }
        if (['gif', 'jpg', 'jpeg', 'png'].includes(fileObj.type)) {
          html += '<img src="' + (fileObj.src || fileObj.base64) + '" >'
        } else {
          //这边因为本地展示没用static
          if (['docx', 'doc'].includes(fileObj.type)) {
            html += '<img src="/static/images/fileType/word.png" title="' + fileObj.name + '">'
          } else if (['zip', 'rar'].includes(fileObj.type)) {
            html += '<img src="/static/images/fileType/zip.png" title="' + fileObj.name + '">'
          } else if (fileObj.type == 'pdf') {
            html += '<img src="/static/images/fileType/pdf.png" title="' + fileObj.name + '">'
          } else if (['xls', 'xlsx'].includes(fileObj.type)) {
            html += '<img src="/static/images/fileType/excel.png" title="' + fileObj.name + '">'
          } else {
            html += '<img src="/static/images/fileType/other.png" title="' + fileObj.name + '">'
          }
        }
        if (!options.readonly) {
          html += '<span class="iconfont icon-close-r closePic"></span>'
        }
        if (options.showName) {
          html += '<div class="fileName">' + fileObj.name + '</div>'
        }
        html += '</div>'
        return html;
      }
      function initView(file) {
        var type = file.type;
        var reader = new FileReader();
        reader.readAsDataURL(file.source.source);
        reader.onload = function (e) {
          var base64 = e.target.result;
          uploaderFiles.push({ size: file.size, base64: base64, name: file.name, type: file.ext, id: file.id, file: file });
          if (options.viewType == 'list') {
            var html = ''
            if (type.includes('image')) {
              html = initHtml({ size: file.size, base64: base64, name: file.name, type: file.ext, id: file.id });
            } else {
              html = initHtml({ size: file.size, base64: base64, name: file.name, type: file.ext, id: file.id });
            }
            filePicker.before(html);
            bindFileEvent();
          } else {
            $(options.picker).hide();
          }


        }
      };
      function initStaticView(dataList) {
        var html = '';
        if (!dataList) {
          dataList = options.fileData || []
        }
        if (dataList.length) {
          for (var i in dataList) {
            var fileItem = dataList[i];
            html += initHtml(fileItem);
            uploaderFiles.push(fileItem)
          }
        }
        filePicker.before(html);
        bindFileEvent();
      }

      function bindFileEvent() {
        var queuedObj = uploader.getStats();
        if (uploaderFiles.length >= settings.fileNumLimit) {
          initUploadBtn('hide');
        }
        filePicker.parent(".picListBox").off('click', '.closePic').on('click', '.closePic', function () {
          var fileObj = null;
          queuedObj = uploader.getStats();
          if (uploaderFiles.length && $(this).parent().data('id')) {
            var id = $(this).parent().data('id');
            var delInd = -1;
            uploaderFiles.forEach(function (v, i) {
              if (v.id == id) {
                fileObj = v;
                delInd = i;
              }
            })
          }
          if (!fileObj) return false;
          fileObj.delFileDom = $(this);
          fileObj.delFileIndex = delInd;
          if (options.beforeRemove) {
            options.beforeRemove(fileObj);
          } else {
            uploader.deleteFile(fileObj);
          }

        })
      }
      function initUploadBtn(type) {
        if (type == 'hide') {
          if (filePicker.length) {
            filePicker.hide()
          } else {
            $(options.picker).parent().hide()
          }
        } else if (type == 'show') {
          if (filePicker.length) {
            filePicker.show()
          } else {
            $(options.picker).parent().show()
          }
        }

      }
      if (options.readonly) {
        initStaticView();
        $(options.picker).addClass('notallowed')
        setTimeout(function () {
          $(options.picker).empty()
        }, 500);
      }
      uploader.on('beforeFileQueued', function (file) {
        if (options.viewType == 'once' && uploaderFiles[0]) {
          uploader.removeFile(uploaderFiles[0].file);
        }
        //console.log(file)

      });
      uploader.on('fileQueued', function (file) {
        console.log(file)
        if (options.beforeUpload) {
          var res = options.beforeUpload(file);
          if (res) {
            initView(file);
          }
        } else {
          initView(file);
        }
      });
      uploader.on('error', function (type) {
        var error = ''
        if (type == "Q_TYPE_DENIED") {
          //error = '请上传' + ( options.fileTypes ? options.fileTypes : settings.accept.extensions ) + '格式文件'
          error = '请上传' + settings.accept.extensions + '格式文件'
        } else if (type == "F_EXCEED_SIZE") {
          error = '文件大小不能超过' + options.fileSize + 'M'
        } else if (type == "Q_EXCEED_NUM_LIMIT") {
          error = '上传文件最多支持' + settings.fileNumLimit + '个'
        } else {
          error = '未知错误'
        }
        //提示层
        if (error) {
          $.myAlert({
            message: error,
            type: 'danger'
          })
        }
      })
      //自定义事件
      uploader.getFiles = function () {
        return uploaderFiles || []
      }
      //更新数据
      uploader.updateFiles = function (dataList, needClear) {
        //如果没数据就不做任何处理
        if (!dataList || dataList.length == 0) {
          return;
        }
        if (needClear) {
          uploader.clearFiles();
        }
        if (options.fileNums) {
          if ((dataList.length + uploaderFiles.length) >= options.fileNums) {
            initUploadBtn('hide');
          } else {
            initUploadBtn('show')
          }
        }
        initStaticView(dataList)

      }
      //删除文件
      uploader.deleteFile = function (fileObj) {
        var delInd = fileObj.delFileIndex;
        var $dom = fileObj.delFileDom
        $dom.parent().remove();
        delInd >= 0 && uploaderFiles.splice(delInd, 1);
        if (fileObj.file) {
          uploader.cancelFile(fileObj.file);
        }
        if (uploaderFiles.length < uploader.options.fileNumLimit) {
          initUploadBtn('show');
        }
      }
      //清空当前的队列及input数据
      uploader.clearInput = function () {
        if (uploaderFiles[0]) {
          uploader.cancelFile(uploaderFiles[0].file);
          uploaderFiles = [];
        }
        filePicker.find('input').val('');

      }
      //清除数据
      uploader.clearFiles = function () {
        filePicker.prevAll().remove();
        if (!options.readonly) {
          filePicker.show();
        }

        uploaderFiles = [];
      }
      // uploader.on()
      // uploader.destroy();
      return uploader;
    },
  });
  $.fn.extend({
    /**省市区 */
    initProvince: function (options) {
      if (!options) options = {};
      var settings = {
        type: options.type || 'static',
        height: options.height || 200,
        codes: options.codes || [],//初始化值
        data: options.data || [],//省市区数据
        getData: options.getData || null,
        disabled: options.disabled || false,
        autoWidth: options.autoWidth || false,//宽度
      }
      var $id;
      var areaList = [];
      if (options.id) {
        $id = $("#" + options.id)
      } else {
        $id = $(this)
      }
      if (settings.data.length) {
        areaList = settings.data
      }
      if (!areaList.length) {
        return false;
      }
      if (options.disabled) {
        $id.attr('disabled', true)
      } else {
        $id.removeAttr('disabled')
      }
      var values = [];//存储选择的值 名称
      var codes = settings.codes;//存储id
      var activeIndex = 0;//当前循环的数据
      var operData = areaList;//初始化默认值的时候要用
      //这边是获取input的默认值
      if ($(this).data('codes')) {
        codes = $(this).data('codes').split(',');
      }
      var boxId = options.id + '_comProviceBox';//最外层div的id
      var pId = options.id + '_provice';//ul省份的Id
      var cId = options.id + '_city';//ul城市的Id
      var aId = options.id + '_area';//ul区域的Id
      var $viewBox = $("#" + boxId);
      //循环生成dom点
      var activeItem = {}
      function setHtm(dataList, index, id) {
        var ulId = options.id + '_ulItem_' + index;
        var comhtm = ''
        var listStyle = ''
        if (settings.autoWidth) {
          listStyle = 'width:auto;'
        }
        var list = JSON.parse(JSON.stringify(dataList))
        comhtm += '<ul class="listBox" style="' + listStyle + '" id="' + ulId + '">'
        for (var i in list) {
          var item = list[i]
          var _class = ''
          if (item.id * 1 == id * 1) {
            _class = 'active'
            activeIndex = i;
            activeItem = item
            values.push(item.name)
          }
          // if (item.children) {
          //   delete item.children
          // }
          comhtm += "<li class='" + _class + "' data-item='" + JSON.stringify(item) + "' data-index='" + i + "'>" + item.name + "</li>"
        }
        comhtm += '</ul>'
        return comhtm;
      }
      //轮询数据获取当前点击的子集
      function getChildData(list, ind) {
        var _list = [];
        function loopData(list, ind) {
          var index = 0;
          for (var i = 0; i < codes.length; i++) {
            var _data = list.find(function (item) { return item.id == codes[i] });
            if (_data) {
              if (_data.children && _data.children.length) {
                _list = _data.children
              } else {
                _list = []
              }
              index = i;
              break;
            }
          }
          if (index < ind) {
            loopData(_list, ind)
          }
        }
        loopData(list, ind);
        return _list

      }
      var htm = '<div id="' + boxId + '" class="comProviceBox" style="height:' + settings.height + 'px;">';
      //有默认值的时候初始化
      if (codes.length) {
        var c_ind = 0;
        htm += setHtm(operData, c_ind, codes[c_ind]);
        c_ind++;
        while (codes[c_ind]) {
          if (activeItem.children && activeItem.children.length) {
            htm += setHtm(activeItem.children, c_ind, codes[c_ind]);
          } else if (activeItem && activeItem.id && settings.getData) {
            operData = settings.getData(activeItem)
            htm += setHtm(operData, c_ind, codes[c_ind]);
          }
          c_ind++;
        }
        //input绑定初始化值
        $("#" + options.id).val(values.join('/')).data('code', codes.join(','))
        if (!options.disabled) {
          $("#" + options.id).prev().show();
        }


      } else {
        htm += setHtm(areaList, 0);
      }
      htm += '</div>'
      if ($("#" + pId).length) {
        $("#" + pId).remove()
      }
      //第一次载入dom
      $id.after(htm);
      var chooseItem = {};
      var chooseData = JSON.parse(JSON.stringify(areaList));
      //input的点击事件
      $("#" + options.id).off('click').on('click', function (e) {
        if (options.disabled) {
          return false;
        }
        $("#" + boxId).slideDown();
        // codes = $(e.target).data('code') ? $(this).data('code').split(',') : [];
        if (!codes.length) {
          $("#" + options.id + "_ulItem_0").nextAll().remove();
          $("#" + options.id + "_ulItem_0").find('.active').removeClass('active');
          chooseItem = {};
          codes = [];
          values = [];
        }
      })
      //点击document关闭弹窗
      document.addEventListener('click', function (event) {
        var targetElement = event.target;  // 获取点击的源元素
        var containerElement = $("#" + options.id).parent().get(0);  // 目标元素
        if (!containerElement.contains(targetElement)) {
          $("#" + boxId).slideUp();
        }
      })
      var noChildVal = function (p_ind, $dom) {
        values = values.filter(function (v, i) { return i <= p_ind });
        codes = codes.filter(function (v, i) { return i <= p_ind });
        $dom.nextAll().remove();
        $("#" + options.id).val(values.join('/')).data('code', codes.join(','))
        $("#" + options.id).prev().show();
        $("#" + boxId).slideUp();
      }
      //省市区的选择事件
      $("#" + boxId).off('click', 'li').on('click', 'li', function (e) {
        //父亲节点
        var $ul = $(e.target).parent('.listBox');
        $(e.target).addClass('active').siblings().removeClass('active');
        var p_ind = $ul.index();
        var index = $(e.target).data('index');
        chooseItem = $(e.target).data('item');
        //储存数据
        codes[p_ind] = chooseItem.id;
        values[p_ind] = chooseItem.name;
        var childList = chooseItem.children ? getChildData(chooseData, p_ind) : [];
        //这边动态加载
        if (chooseItem && chooseItem.id && settings.getData) {
          // settings.getData(chooseItem).then(function (res) {
          childList = settings.getData(chooseItem) || [];
          if (childList.length) {
            var c_htm = setHtm(childList, (p_ind + 1));
            $ul.nextAll().remove()
            $ul.after(c_htm);
          } else {
            noChildVal(p_ind, $ul)
          }
          // })
        } else {//这边静态数据
          if (childList.length) {
            var c_htm = setHtm(childList, (p_ind + 1));
            $ul.nextAll().remove()
            $ul.after(c_htm);
          } else {
            noChildVal(p_ind, $ul)
          }
        }
      })

    },
    /**日期控件初始化 */
    datePicker: function (options) {
      var id = $(this).attr("id");
      var random = new Date().getTime();
      var settings = {
        language: "zh-CN",
        format: "yyyy-mm-dd hh:ii:ss",
        formatTime: 'hh:ii',
        // formatType: '',
        formatDate: 'yyyy-mm-dd',
        // weekStart: 1,
        todayBtn: 1, //显示当天按钮，点击则选择当天当天时间
        autoclose: 1, //选完时间自动关闭
        todayHighlight: 1, //当天时间高亮
        // startView: 1, //从月视图开始，选天 [hour,day,month,year,decade]
        // minView: 0, //提供选择分钟的视图  数据同上
        // maxView: 4,
        enableOnReadonly: options.disabled || false,
        disabled: options.disabled || false,
        forceParse: 1, //强制解析输入的日期
        pickerPosition: "bottom-right",
        todayBtn: true, //底部按钮
        todayBtn: true, //高亮显示当前日期
        // startDate: "", //最小时间限制
        // endDate: "",//最大时间限制
        // minDate:'',//允许选择的最小时间
        // maxDate:'',//y允许选择的最大时间
        // daysOfWeekDisabled:'',//设置禁止选择的星期几
        minuteStep: 5, //用于构建小时视图。就是最小的视图是每1分钟可选一次。是以分钟为单位的
        useCurrent: false,
        icons: {
          time: "iconfont icon-timer1",
          date: "iconfont icon-timer2",
          // up: "fa fa-arrow-up",
          // down: "fa fa-arrow-down",
          // previous: "fa fa-chevron-left",
          // next: "fa fa-chevron-right",
          // today: "fa fa-clock-o",
          // clear: "fa fa-trash-o"
        },
      };
      switch (options.format) {

        case "date":
          settings.format = "yyyy-mm-dd";
          settings.minView = 2;
          settings.maxView = 4;
          break;
        case "datetime":
          settings.format = "yyyy-mm-dd hh:ii:ss";
          settings.minView = 0;
          settings.maxView = 4;
          break;
        case "datemin":
          settings.format = "yyyy-mm-dd hh:ii";
          settings.minView = 0;
          settings.maxView = 4;
          break;
        default:
          break;
      }
      if (options.dateType == "date") {
        var inputId = id + random;
        $(this).addClass("relative");
        $(this).html(
          '<input type="text" placeholder="请选择日期" style="padding-right:30px;" class="form-control fullWidth" id="' +
          inputId +
          '" /><span class="add-on"><i class="iconfont icon-timer2"></i></span>'
        );
        if (options.value) {
          $("#" + inputId).value();
        }
        $("#" + inputId).datetimepicker(settings);
      } else if (options.dateType == "daterange") {
        settings.pickerPosition = "bottom-left";
        $(this).addClass("flex");
        $(this).css('min-width', '50%')
        var startId = id + "Begin" + random;
        var endId = id + "End" + random;
        $(this).html(
          '<div class="relative flex-1"><input type="text" placeholder="请选择开始日期" style="padding-right:30px;" class="startTime flex-1 form-control" id="' +
          startId +
          '" /><span class="add-on"><i class="iconfont icon-timer2"></i></span></div>' +
          '<span class="dateText" style="margin:0 5px;line-height:32px;">至</span>' +
          '<div class="relative flex-1"><input type="text" style="padding-right:30px;" placeholder="请选择结束日期" class="endTime flex-1 form-control" id="' +
          endId +
          '" /><span class="add-on"><i class="iconfont icon-timer2"></i></span></div>'
        );
        if (options.rangeValue) {
          $("#" + startId).val(options.rangeValue[0] || "");
          $("#" + endId).val(options.rangeValue[1] || "");
        }
        $("#" + startId)
          .datetimepicker(settings)
          .on("changeDate", function (ev) {
            var s_time = $(this).val();
            var endTime = $("#" + endId).val();
            if (endTime) {
              var date = new Date(endTime.replace(/-/g, "/"));
              if (date != "Invalid Date" && date < ev.date) {
                $(this).val("");
                $.myAlert({
                  message: "开始日期必须小于结束日期,请重新选择！",
                  type: "danger",
                });
              }
            }
          });
        $("#" + endId)
          .datetimepicker(settings)
          .on("changeDate", function (ev) {
            var s_time = $("#" + startId).val();
            var e_time = $(this).val();
            if (s_time) {
              var date = new Date(s_time.replace(/-/g, "/"));
              if (date != "Invalid Date" && date > ev.date) {
                $(this).val("");
                $.myAlert({
                  message: "结束日期必须大于开始日期,请重新选择！",
                  type: "danger",
                });
              }
            }
          });
        $(".add-on")
          .off("click")
          .on("click", function () {
            $(this).siblings("input").triggerHandler("focus");
          });
      }
    },
    /**layui日期组件封装 */
    initDatePicker: function (options) {
      var id = $(this).attr('id');
      var t = $.Deferred();
      layui.use(function () {
        var laydate = layui.laydate;
        var settings = {
          elem: '#' + id,
          type: options.type || 'date',//year 年，month年月，time 时分秒，datetime完整事件
          range: options.range || false,//时间范围两个input的id
          rangeLinked: options.range ? true : false,
          format: '',
          value: options.value || '',
          trigger: 'click',// 默认：focus
          show: false,//直接显示日期
          position: 'abolute',//  fixed
          isPreview: options.isPreview || false,
          showBottom: options.showBottom || options.showBottom == undefined ? true : false,
          btns: options.btns || ['clear', 'now', 'confirm'],
          theme: '#1890ff',
          calendar: false,//公历
          mark: { //自定义重要日子
            // '0-10-14': '生日'
          },
          ready: function (date) {
            if (options.ready) {
              return options.ready(date)
            }
          },
          change: function (value, date, endDate) {
            if (options.change) {
              return options.change(value, date, endDate)
            }
          },
          done: function (value, date, endDate) {
            if (options.callback) {
              return options.callback(value, date, endDate)
            }
          },
        }
        var format = '';
        switch (settings.type) {
          case 'year':
            format = 'yyyy'
            break;
          case 'month':
            format = 'yyyy-MM'
            break;
          case 'time':
            format = 'HH:mm:ss'
            break;
          case 'datetime':
            format = 'yyyy-MM-dd HH:mm:ss'
            break;
          default:
            format = 'yyyy-MM-dd'
            break;
        }
        settings.format = format;
        laydate.render(settings);
        t.resolve(laydate)
      })
      return t;
    },
    /**日期控件赋值 */
    setDatePickeValue: function (val) {
      // if (val) {
      if (typeof val == "object") {
        $(this)
          .find(".startTime")
          .val(val[0] || "");
        $(this)
          .find(".endTime")
          .val(val[1] || "");
      } else if (typeof val == "string") {
        $(this).find("input").val(val || '');
      }
      // }
    },
    /**日期控件取值 */
    getDatePickeValue: function () {
      var _input = $(this).find("input");
      if (_input && _input.length == 1) {
        return _input.val();
      } else {
        return [
          $(this).find(".startTime").val(),
          $(this).find(".endTime").val(),
        ];
      }
    },
    getSelectValue: function (e) {
      var _data = $(this).data();
      var val = _data.selectdata;
      var datatype = _data.datatype;
      var id = $(this).attr('id');
      var dataList = window[id] || [];
      var list;
      if (Array.isArray(val)) {
        list = val;
      } else {
        list = val ? val.split(',') : [];
      }
      var res = [];
      var dataHash = {};
      $.each(dataList.data, function (dk, dv) {
        dataHash["" + dk] = dv;
      })
      list.forEach(function (v) {
        /*var item = dataList.data.find(function (_data) {
          return _data.id == v
        })*/
        var item = dataHash[v + ""];
        if (item) res.push(item)
      })
      if (datatype == 'string') {
        return list.join(',');
      } else {
        return res;
      }

    },
    setSelectValue: function (val) {
      if (typeof (val) == 'string') {
        val = val.split(',');
      }
      if (Array.isArray(val)) {
        val.forEach(function (v) {
          v += ''
        })
      } else {
        //val += "";
        val = [val + ""];
      }

      //val.forEach(function (v) {
      //  v += ''
      //})
      $(this).data('selectdata', val);
      var settings = window[$(this).attr('id')];
      var list = settings.data;
      var textList = [];
      for (var i in list) {
        var item = list[i];
        var name = item[settings.showName];
        var id = item[settings.showValue] + '';
        if (val.includes(id)) {
          textList.push(name);
        }
      }
      if (textList.length) {
        $(this).find("input").val(textList.join(','));
        $(this).find(".iconClose").fadeIn('fast');
      }
    },
    /**下拉组件 */
    comSelect: function (options) {
      var $this = $(this);
      var settings = {
        id: options.id || $this.attr('id'),
        showName: options.showName || "name",
        showValue: options.showValue || "id",
        showPinyin: options.showPinyin || 'code',
        defaultVal: options.defaultVal || null,
        height: options.height || 200,
        data: options.data || [],
        mutiselect: options.mutiselect || false,
        pySearch: options.pySearch || false,//是否支持拼搜索
        inputClass: options.inputClass || ' ',			//	input的自定义样式
        dataType: options.dataType || 'string',//获取数据返回的类型  object 返回的完整数据数组  string  返回的都好隔开id 
      };

      options.isSelected = false;
      // var pinyin = pinyinPro.pinyin;
      var textList = [];
      var selectdata = $this.data('selectdata') ? $this.data('selectdata').split(',') : [];
      var valList = options.defaultVal || selectdata;
      for (var i in valList) {
        valList[i] = String(valList[i])
      }
      for (var i in settings.data) {
        var item = settings.data[i];
        var name = item[settings.showName];
        if (valList.includes(String(item[settings.showValue]))) {
          textList.push(name);
        }
        if (settings.pySearch) {
          var _code = item[settings.showPinyin] ? item[settings.showPinyin] : '';
          item.showText = _code + '&nbsp;&nbsp;' + item[settings.showName];
          item.filterVal = _code.toLowerCase() + item[settings.showName];
          // item.fullpy = pinyin(name, { toneType: "none", type: "array" }).join('');
          // item.simplepy = pinyin(name, { pattern: "initial", type: "array" }).join('');
          item.nameCN = item[settings.showName];
        }
      }
      var cacheData = JSON.parse(JSON.stringify(settings.data || []));
      options.data = settings.data;
      window[settings.id] = settings;
      $this.data('datatype', settings.dataType)
      $this.data('type', settings.mutiselect ? 'checkbox' : 'radio')
      var htm = "";
      htm +=
        '<div class="comSelectInput">' +
        '<input class="form-control ' + settings.inputClass + '" placeholder="请选择"/><span class="iconfont icon-close-X iconClose"></span><span class="iconfont icon-arrow-down"></span></div>';
      $this.html(htm)
      if (textList && textList.length) {
        $this.find("input").val(textList.join(','));
        $this.find(".iconClose").fadeIn('fast');
      }
      var $ul = '<ul class="comSelectDownList" style="width:' + $this.width() + 'px;height:' + options.height + 'px">"</ul>'
      $this.append($ul);
      function initLisyt(dataList, noVla) {
        var list_htm = '';
        // 重新设置下拉框宽度
        $this.find(".comSelectDownList").width($this.width());
        for (var i in dataList) {
          var item = dataList[i];
          var li_class = '', span_check = '';
          if (!noVla) {
            if (valList.includes(String(item.id))) {
              item.isChecked = true;
            } else {
              item.isChecked = false;
            }
          }

          if (item.isChecked) {
            li_class = ' active'
          }
          //TODO 多选
          if (settings.mutiselect) {
            if (item.isChecked) {
              span_check = 'icon-checked-full'
            } else {
              span_check = 'icon-check'
            }
            list_htm +=
              "<li class='comSelectItem checkBoxItem" + li_class + "' data-value='" +
              item[settings.showValue] +
              "' title='" + (item.showText || item[settings.showName]) + "'>" +
              "<span class='iconfont " + span_check + "'></span><span class='text'>" +
              item.showText || item[settings.showName] +
              "</span></li>";
          } else {
            list_htm +=
              "<li class='comSelectItem" + li_class + "' data-value='" +
              item[settings.showValue] +
              "'>" +
              item.showText || item[settings.showName] +
              "</li>";
          }
        }
        $this.children('.comSelectDownList').html(list_htm);
      }

      //input 点击
      $this
        .off("click", ".form-control")
        .on("click", ".form-control", function () {
          var val = $(this).val();
          var _clicklist = options.data;
          $this.children('.comSelectDownList').html('');
          if (val && settings.pySearch) {
            // $(this).val('')
            //input 输入
            _clicklist = pyFilter(options.data, val, true)
            if (_clicklist.length == 0) {
              $.myAlert({
                type: 'warning',
                message: '暂无相关数据！'
              })
            }
          }
          initLisyt(_clicklist, true);
          $this.addClass("comSelectBox_click");
          $this
            .children(".comSelectDownList")
            .fadeIn();
          $(document).off('keydown', $(this)).on('keydown', $(this), function (event) {
            console.log(event.key)
            if (event.key == 'Delete' || event.key == 'Backspace') {
              clearSelect();
              initLisyt(options.data);
            }
          });
        });
      $(this).find('.form-control').off('input').on('input', function () {
        var inputVal = $(this).val();
        var oldText = textList;
        if (typeof (textList) == 'object') {
          oldText = textList.join(',')
        }
        if (inputVal) {
          if (oldText && oldText !== inputVal) {
            inputVal = '';
            $(this).val('');
            clearSelect();
          }
          var _list = pyFilter(settings.data, inputVal)
          settings.data = _list
          $this.children('.comSelectDownList').html('');
          initLisyt(_list)
        } else {
          settings.data = options.data;
          clearSelect();
          initLisyt(settings.data)
        }

      })
      $this
        .off("click", ".iconClose`")
        .on("click", ".iconClose", function (e) {
          e.stopPropagation()
          e.preventDefault()
          clearSelect();

        });
      $(document).on('click', function (e) {
        var targetElement = e.target;  // 获取点击的源元素
        // var containerElement = $this.get();  // 目标元素
        if ($this[0] && targetElement && !$this[0].contains(targetElement)) {
          $this.removeClass("comSelectBox_click");
          setTimeout(function () {
            $this
              .find(".comSelectDownList")
              .fadeOut('fast');
          }, 200);
        }
      })
      $(parent.document).on('click', function (e) {
        var targetElement = e.target;  // 获取点击的源元素
        if ($this[0] && targetElement && !$this[0].contains(targetElement)) {
          $this.removeClass("comSelectBox_click");
          setTimeout(function () {
            $this
              .find(".comSelectDownList")
              .fadeOut('fast');
          }, 200);
        }
      })
      $this
        .off("click", ".comSelectItem")
        .on("click", ".comSelectItem", function () {
          options.isSelected = true;
          var ind = $(this).index();
          if (settings.mutiselect) {
            $(this).toggleClass("active");
          } else {
            $this.removeClass("comSelectBox_click");
            $(this).toggleClass("active").siblings().removeClass("active");
            $(this).parent("ul").fadeOut('fast');
          }
          var items = []
          var textarr = [];
          if ($(this).hasClass("active")) {
            settings.data[ind].isChecked = true;
            if (settings.mutiselect) {
              $(this).find('.iconfont').removeClass('icon-check').addClass('icon-checked-full');
              for (var i in settings.data) {
                var item = settings.data[i];
                if (item.isChecked) {
                  textarr.push(item[settings.showName])
                  items.push(item[settings.showValue])
                }
              }
              $this
                .find("input")
                .val(textarr.join(','));
            } else {
              for (var i in settings.data) {
                if (i * 1 !== ind) {
                  settings.data[i].isChecked = false;
                }
              }
              textarr.push(settings.data[ind][settings.showName])
              items.push(settings.data[ind][settings.showValue])
              $this
                .find("input")
                .val(settings.data[ind][settings.showName]);
            }
            $this.find(".iconClose").fadeIn()
          } else {
            settings.data[ind].isChecked = false;
            if (settings.mutiselect) {
              $(this).find('.iconfont').removeClass('icon-checked-full').addClass('icon-check');
              for (var i in settings.data) {
                var item = settings.data[i];
                if (item.isChecked) {
                  textarr.push(item[settings.showName]);
                  items.push(item[settings.showValue]);
                }
              }
              $this
                .find("input")
                .val(textarr.join(','));
              if (textarr.length == 0) {
                $this
                  .find(".iconClose").hide()
              }
            } else {
              clearSelect();
            }
          }
          if (items.length) {
            $this.data('selectdata', items.join(','))
          } else {
            $this.data('selectdata', '');
          }
          valList = items;
          textList = textarr;
          settings.defaultVal = items;

        });
      //筛选
      function pyFilter(dataList, inputVal, needSelect) {
        dataList = options.data;
        var newArrange = [];
        if (inputVal) {
          inputVal = inputVal.toLowerCase();  //split("");
          // var str = "(.*?)";//正则条件
          // var regStr = str + inputArr.join(str) + str;
          // var reg = RegExp(regStr, "i");
          dataList.forEach(function (item, ind) {
            var nameCN = item.nameCN
            var filterVal = item.filterVal
            var code = item[settings.showPinyin];
            // var dataPy = item.fullpy;
            // var siplePy = item.simplepy;
            //|| reg.test(siplePy)
            if (needSelect) {
              item.isChecked = settings.defaultVal && settings.defaultVal.includes(item[settings.showValue])
              newArrange.push(item);
            } else if (filterVal.indexOf(inputVal) >= 0) {
              newArrange.push(item);
            }
          })
        } else {
          newArrange = dataList
        }
        return newArrange;
      }
      //清楚选择
      function clearSelect() {
        settings.data.forEach(function (v, i) {
          v.isChecked = false;
        })
        options.data.forEach(function (v, i) {
          v.isChecked = false;
        })
        valList = [];
        textList = [];
        settings.defaultVal = [];
        $this.data('selectdata', '');
        $this.find("input").val('');
        $this.find(".iconClose").fadeOut('fast');
        $this.find('.comSelectItem').removeClass('active');
        $this.find('.comSelectItem').find('.iconfont').removeClass('icon-checked-full').addClass('icon-check');
      }
    },
  });
  // bindComEvent();
  // 开始录制
  // startRecording();
})(jQuery);

